package config

import (
	"encoding/json"
	"log"
	"os"
	"sync"

	"github.com/gin-gonic/gin"
)

// Configuration 项目配置
type Configuration struct {
	// gtp apikey
	AccessKey string `json:"access-key"`
	// 启动服务端口
	SecretKey string `json:"secret-key"`
	// Gin Mode
	HttpPort string `json:"port"`
	// Gin Mode
	GinMode string `json:"gin_mode"`
}

var config *Configuration
var once sync.Once

// LoadConfig 加载配置
func LoadConfig() *Configuration {
	once.Do(func() {
		// 从文件中读取
		config = &Configuration{}
		f, err := os.Open("config.json")
		if err != nil {
			log.Fatalf("open config err: %v", err)
			return
		}
		defer f.Close()
		encoder := json.NewDecoder(f)
		err = encoder.Decode(config)
		if err != nil {
			log.Fatalf("decode config err: %v", err)
			return
		}

		// 如果环境变量有配置，读取环境变量
		AccessKey := os.Getenv("AccessKey")
		SecretKey := os.Getenv("SecretKey")
		HttpPort := os.Getenv("HttpPort")
		GinMode := os.Getenv("GinMode")

		if AccessKey != "" {
			config.AccessKey = AccessKey
		}
		if SecretKey != "" {
			config.SecretKey = SecretKey
		}
		if HttpPort != "" {
			config.HttpPort = HttpPort
		}
		if GinMode != "" {
			gin.SetMode(GinMode)
		}
	})
	return config
}
